
package com.jf.cloud.user.controller.app;


import com.jf.cloud.api.auth.bo.UserInfoInTokenBO;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.auth.feign.AccountFeignClient;
import com.jf.cloud.api.auth.vo.TokenInfoVO;
import com.jf.cloud.api.biz.feign.NotifyFeignClient;
import com.jf.cloud.api.user.bo.UidAndUserIdBO;
import com.jf.cloud.api.user.dto.UserRegisterDTO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.user.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 用户信息
 * @author zz
 */
@RestController
@RequestMapping("/ua/user/register")
@Tag(name = "app-用户注册接口")
public class UserRegisterController {

    @Autowired
    private  UserService userService;
    @Autowired
    private AccountFeignClient accountFeignClient;
    @Autowired
    private NotifyFeignClient notifyFeignClient;

    /**
     * 注册的头像昵称有几个值得注意的地方：
     * 1. 如果是微信公众号 or 小程序注册，在注册之前，也就是在进入页面之前，需要调用SocialLoginController 这里面的尝试登录的接口，如果可以登录就直接登录了。
     * 2. 关于发送验证码
     *    1) 如果用邮箱进行注册就发送邮箱验证码
     *    2) 手机号注册,要发送验证码
     * 3. 当注册成功的时候，已经返回token，相对来说，已经登录了
     */
    @Operation(summary = "注册")
    @PostMapping
    public ServerResponseEntity<TokenInfoVO> register(@Valid @RequestBody UserRegisterDTO param) {
        // 手机号校验
        ServerResponseEntity<Boolean> validCodeResponse = notifyFeignClient.checkValidCodeByFlag(param.getMobile(), param.getCheckRegisterSmsFlag());
        if (!validCodeResponse.isSuccess() || !validCodeResponse.getData()) {
            return ServerResponseEntity.fail(ResponseEnum.VERIFICATION_CODE_ERROR);
        }
        // 1. 保存账户信息
        UidAndUserIdBO uidAndUserIdBO = userService.save(param.getMobile(), param.getPassword(), null);


        UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
        userInfoInTokenBO.setUid(uidAndUserIdBO.getUid());
        userInfoInTokenBO.setUserId(uidAndUserIdBO.getUserId());
        userInfoInTokenBO.setSysType(SysTypeEnum.ORDINARY.value());
        userInfoInTokenBO.setIsAdmin(0);
        // 2. 登录
        return accountFeignClient.storeTokenAndGetVo(userInfoInTokenBO);
    }

}
